package com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp20.handler;

import com.caiyi.financial.nirvana.sms.gateway.DefaultGateWay;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.GatewayControlHandler;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp20.message.CMPPMessage;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp20.message.body.CMPPActiveTest;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp20.message.body.CMPPConnection;
import com.caiyi.financial.nirvana.sms.util.Constant;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * CMPP协议总控制器
 *
 * @author lvchaohua
 */
public class CMPPControlHandler extends GatewayControlHandler {

    private final static Logger logger = LogManager.getLogger(CMPPControlHandler.class);

    public CMPPControlHandler(DefaultGateWay gateWayInfo) {
        this.gateWayInfo = gateWayInfo;
    }

    //登录
    @Override
    public void doLogin(ChannelHandlerContext ctx) {
        int sequenceId = Constant.seqNo.incrementAndGet();
        logger.info(gateWayInfo.info.getName() + " 正在登录。。。sequenceId : {}", sequenceId);
        CMPPMessage loginMessage = new CMPPMessage();
        CMPPConnection cmppConnection = new CMPPConnection(gateWayInfo.info.getAccount(), gateWayInfo.info.getPassword());
        loginMessage.setCommandID(CMPPMessage.CMPP_CONNECT);
        loginMessage.setSequenceId(sequenceId);
        loginMessage.setBody(cmppConnection);
        ctx.writeAndFlush(loginMessage);
    }

    //心跳
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            //读空闲事件，触发重连，关闭当前连接；否则发送心跳包给服务器
            if (event.state().equals(IdleState.READER_IDLE)) {
                logger.info(gateWayInfo.info.getName() + " 触发读空闲事件，连接关闭！");
                ctx.close();
            } else {
                logger.info(gateWayInfo.info.getName() + " 触发心跳测试。");
                CMPPMessage message = new CMPPMessage();
                message.setCommandID(CMPPMessage.CMPP_ACTIVE_TEST);
                message.setSequenceId(Constant.seqNo.incrementAndGet());
                CMPPActiveTest activeTest = new CMPPActiveTest();
                message.setBody(activeTest);
                ctx.writeAndFlush(message);
            }
        }
    }

}
